package com.jn.erp.web.api.sys.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jn.erp.common.annotation.Log;
import com.jn.erp.common.core.result.AjaxResult;
import com.jn.erp.common.enums.BusinessType;
import com.jn.erp.common.utils.StringUtils;
import com.jn.erp.common.utils.file.MimeTypeUtils;
import com.jn.erp.security.controller.BaseWebAuthController;
import com.jn.erp.security.entity.LoginUser;
import com.jn.erp.security.entity.SysRole;
import com.jn.erp.security.entity.SysUser;
import com.jn.erp.security.entity.SysUserRole;
import com.jn.erp.security.service.TokenService;
import com.jn.erp.security.sysservice.SysRoleService;
import com.jn.erp.security.sysservice.SysUserRoleService;
import com.jn.erp.security.sysservice.SysUserService;
import com.jn.erp.security.utils.SecurityUtils;
import com.jn.erp.utils.file.FileUploadUtils;
import com.jn.erp.web.api.sys.entity.SysOrgUser;
import com.jn.erp.web.api.sys.service.SysOrgUserService;
import com.jn.erp.web.configuration.JNConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 个人信息 业务处理
 */
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseWebAuthController {
    @Autowired
    private SysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysOrgUserService sysOrgUserService;


    /**
     * 个人信息
     */
    @GetMapping
    public AjaxResult profile() {
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        QueryWrapper<SysOrgUser> qou = new QueryWrapper<>();
        qou.eq("org_id", loginDeptAuth());
        qou.eq("user_id", user.getId());
        SysOrgUser one = sysOrgUserService.getOne(qou);
        user.setNickName(one.getNickName());
        AjaxResult ajax = AjaxResult.success(user);
        QueryWrapper<SysUserRole> qw = new QueryWrapper();
        qw.eq("user_id", loginUser.getUserId());
        if (!StrUtil.equals(loginDeptAuth(), "1")) {
            qw.in("org_id", "1", loginDeptAuth());
        }
        List<SysUserRole> list = sysUserRoleService.list(qw);
        if (CollectionUtils.isEmpty(list)) {
            return error(StringUtils.EMPTY);
        }
        Set<Long> collect = list.stream().map(sr -> sr.getRoleId()).collect(Collectors.toSet());
        QueryWrapper<SysRole> qwr = new QueryWrapper();
        qwr.in("role_id", collect);
        List<SysRole> list1 = sysRoleService.list(qwr);
        if (CollectionUtils.isEmpty(list1)) {
            return error(StringUtils.EMPTY);
        }
        String roleNames = list1.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
        ajax.put("roleGroup", roleNames);
        return ajax;
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysUser user) {
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = userService.getById(loginUser.getUserId());
        currentUser.setEmail(user.getEmail());
        currentUser.setGender(user.getGender());
        currentUser.setMobile(user.getMobile());

        if (StringUtils.isNotEmpty(user.getMobile()) && !userService.checkPhoneUnique(currentUser)) {
            return error("修改用户'" + loginUser.getUsername() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser)) {
            return error("修改用户'" + loginUser.getUsername() + "'失败，邮箱账号已存在");
        }

        if (userService.updateById(currentUser)) {
            // 更新缓存用户信息
            tokenService.setLoginUser(loginUser);
            UpdateWrapper<SysOrgUser> qw = new UpdateWrapper<>();
            qw.set("nick_name", user.getNickName());
            qw.eq("org_id", loginDeptAuth());
            qw.eq("user_id", currentUser.getId());
            sysOrgUserService.update(qw);
            return success();
        }
        return error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword) {
        LoginUser loginUser = getLoginUser();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return error("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        SysUser user = new SysUser();
        user.setId(loginUser.getUserId());
        user.setPassword(newPassword);
        if (userService.updateById(user)) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            LoginUser loginUser = getLoginUser();
            String avatar = FileUploadUtils.upload(JNConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            if (userService.updateUserAvatar(loginUser.getUserId(), avatar)) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }
}
